package cn.bestick.thirteenKiller.service.impl;

import cn.bestick.thirteenKiller.dao.DataBase;
import cn.bestick.thirteenKiller.service.KillerService;
import cn.bestick.thirteenKiller.util.MemoryImage;
import cn.bestick.thirteenKiller.win32.Rect;
import cn.bestick.thirteenKiller.win32.User32;

import javax.swing.*;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.image.BufferedImage;


/**
 * Created by bestick on 2016/1/17.
 */
public class KillerServiceImpl implements KillerService {

    private User32 user32 = User32.INSTANCE;
    private final int X = 304;
    private final int Y = 520;
    private final int W = 436;
    private final int H = 120;

    @Override
    public boolean ms() throws Exception {
        int hwnd = getHwnd();
        if (hwnd == 0) {
            JOptionPane.showMessageDialog(null, "请先打开游戏窗口！", "13killer tip", 0);
            return false;
        }
        MemoryImage mImg = getImage(hwnd);
        getQp(mImg);

        DataBase db = DataBase.getInstance();
        db.saveData("tmp");
        return true;
    }

    private int getHwnd() {
        return this.user32.FindWindowA(null, "thirtn");
    }

    private MemoryImage getImage(int hwnd) {
        Rect r = new Rect();
        this.user32.GetWindowRect(hwnd, r);
        Rectangle rg = new Rectangle(r.left, r.top, r.right - r.left, r.bottom -
                r.top);
        try {
            BufferedImage image = new Robot().createScreenCapture(rg);
            return new MemoryImage(image);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private MemoryImage[] getQp(MemoryImage mImg) throws Exception {
        MemoryImage qpImg = mImg.copy(X, Y, W, H);
        MemoryImage[] mImgArr = new MemoryImage[13];
        for (int x = 0; x < 13; x++) {
            if ((x >= 0) && (x < 4)) {
                mImgArr[x] = qpImg.copy(x * 29 + 5, 5, 10, 26);
                mImgArr[x].write("tmp/" + x + ".jpg");
            } else if ((x >= 4) && (x < 9)) {
                mImgArr[x] = qpImg.copy(x * 29 + 4, 5, 10, 26);
                mImgArr[x].write("tmp/" + x + ".jpg");
            } else {
                mImgArr[x] = qpImg.copy(x * 29 + 3, 5, 10, 26);
                mImgArr[x].write("tmp/" + x + ".jpg");
            }
        }
        return mImgArr;
    }
}
